package com.china_goldcard.mygridview;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckedTextView;

import java.util.List;

/**
 * MyGridViewAdapter
 */

public class MyGridViewAdapter extends BaseAdapter {

    protected Context context;//运行上下文
    protected List<MyGridViewModel> listData;//数据集合
    protected LayoutInflater listContainer;//视图容器
    protected int itemViewResource;//自定义项视图源id

    /**
     * 构造函数
     * @param context
     * @param data
     * @param resource
     */
    public MyGridViewAdapter(Context context, List<MyGridViewModel> data, int resource) {
        this.context = context;
        this.listContainer = LayoutInflater.from(context);	//创建视图容器并设置上下文
        this.itemViewResource = resource;
        this.listData = data;
    }

    /**
     * 重载
     * @param data
     */
    public void reloadData(List<MyGridViewModel> data){
        this.listData = data;
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return listData.size();
    }

    @Override
    public MyGridViewModel getItem(int index) {
        return listData.get(index);
    }

    @Override
    public long getItemId(int index) {
        return index;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder = null;
        if (convertView == null){
            convertView = listContainer.inflate(R.layout.my_grid_item_view,null);
            viewHolder = new ViewHolder();
            viewHolder.textView = (CheckedTextView)convertView.findViewById(R.id.grid_view_item_tv);
            convertView.setTag(viewHolder);
        }else{
            viewHolder = (ViewHolder)convertView.getTag();
        }
        viewHolder.textView.setChecked(listData.get(position).isSelected());
        viewHolder.textView.setText(listData.get(position).getTitle());
        return convertView;
    }

    class ViewHolder{
        CheckedTextView textView;
    }
}
